/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.config.filter;

import com.huawei.housekeeper.model.ListAdminContext;
import com.huawei.housekeeper.constants.CommonConstants;
import com.huawei.housekeeper.utils.CommonUtil;
import com.huawei.housekeeper.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JWT登录授权过滤器
 *
 * @author y00464350
 * @since 2022-02-23
 */
@Log4j2
@RefreshScope
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private HandlerExceptionResolver handlerExceptionResolver;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private ListAdminContext adminContext;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        Thread currentThread = Thread.currentThread();
        currentThread.setName(request.getRequestURI() + ":" + CommonUtil.getUUID());
        String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (authHeader != null && authHeader.startsWith(tokenHead)) {
            String authToken = authHeader.substring(tokenHead.length());
            Claims claims = jwtTokenUtil.getClaimsFromToken(authToken);
            try {
                String userName = jwtTokenUtil.getUserNameFromToken(authToken);
                request.setAttribute(CommonConstants.User.USER_NAME, userName);
                List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_" + claims.get(CommonConstants.User.ROLE));
                grantedAuthorityList.add(grantedAuthority);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        claims.get(CommonConstants.User.USER_NAME), claims.get(CommonConstants.User.USER_PAW), grantedAuthorityList);
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (ExpiredJwtException e) {
                handlerExceptionResolver.resolveException(request, response, null, e);
                return;
            } catch (Exception e) {
                handlerExceptionResolver.resolveException(request, response, null, e);
                log.error(e.getMessage(), e);
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
